import React, { Component } from 'react'
import Taro, { getCurrentInstance, getCurrentPages } from '@tarojs/taro'
import S from '@/spx'
import { Provider } from 'react-redux'
import configStore from '@/store'
import user, { updateMessageNum, updateToday_data } from '@/store/user'
import planSelection from './store/planSelection'
import api from '@/api'
import { checkAppVersion, isWeixin, isWeb, isNavbar, log } from '@/utils'
import { requestIntercept } from '@/plugin/requestIntercept'
import { AtMessage, message } from 'taro-ui'
import './app.scss'
import Vconsole from 'vconsole'
import { functions, values } from 'lodash'

// 如果需要在 h5 环境中开启 React Devtools
// 取消以下注释：
// if (process.env.NODE_ENV !== 'production' && process.env.TARO_ENV === 'h5')  {
//   require('nerv-devtools')
// }
if (process.env.NODE_ENV !== 'production' && process.env.TARO_ENV === 'h5') {
  // const vconsole = new Vconsole()
}

const { store } = configStore()
const __this = this
// 如果是app模式，注入SAPP
if (process.env.APP_BUILD_TARGET == 'app') {
  console.log(process.env.APP_BUILD_TARGET)
  import('@/plugin/app/index').then(({ SAPP }) => {
    console.log(SAPP)
    SAPP.init(Taro, store)
    getAppversionCode()
  })

} else {
  getAppversionCode()
  // import('@/plugin/routeIntercept').then(({ intercept }) => {
  //   intercept.init()
  // })
}
const getAppversionCode = async () => {
  console.log(isAndroid())
  if(!isAndroid()) {
    return
  }
  const result = await api.auth.getAppversionCode()
  console.log('版本信息', result)
  if (Taro.getEnv() == 'SAPP') {
    const verCode = plus.runtime.versionCode//客户端的版本号
    console.log('该手机的code', verCode, plus.runtime.version, plus.runtime.innerVersion)
    // alert(`${verCode},${plus.runtime.version},${plus.runtime.innerVersion}`)
    if (result.code > verCode) {
      showUpdate(result)
    } else {

    }
  }
}

const showUpdate = (result) => {
  Taro.showModal({
    title: '已经有新版本了哟~',
    content: result.content,
    confirmText: '去更新',
    success: function (res) {
      if (res.confirm) {
        //去下载
        console.log(res)
        const isAndr = isAndroid()
        if (isAndr) {
          downloadNewVersion(result.url)
        }

      }

    }
  })
}
const isAndroid = () => {
  var u = navigator.userAgent
  var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1
  var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
  console.log(isAndroid, isiOS)

  // if (isAndroid) {
  //   alert('Android')
  // }else if(isiOS){
  //   alert('iOS')
  // }else{
  //   alert('啥都不是')
  // }
  return isAndroid
}
const downloadNewVersion = (url) => {
  console.log('star////', url)
  var dtask = plus.downloader.createDownload(url, {
    filename: "_downloads/"
  },
    function (d, status) {
      console.log('------d', d)
      // 下载完成
      if (status == 200) {
        plus.runtime.install(d.filename, {
          force: false
        }, function () {
          //进行重新启动;
          // plus.runtime.restart();
        }, (e) => {
          console.log('error', e)
        });
      } else {
        plus.nativeUI.alert("下载升级包失败，请手动去站点下载安装，错误码: " + status);
      }
    })
  dtask.start();

  // console.log(dtask.totalSize, dtask.downloadeSize)
}
// requestIntercept()

// addsoct = () =>{
//   console('121312')
// }
class App extends Component {

  constructor(props) {
    super(props)
    this.state = {
      webSocketIsOpen: false,
      restartOpenWebsoect: true,
      SocketTask: null,
      closeResult: '',
      meesagestr: ''
    }

  }

  async componentDidMount() {
    Taro.getApp().addsoct = () => {
      this.restartOpenWebsoect()
    }
    Taro.getApp().closeSocket = (str) => {
      console.log(str)
      if (this.state.SocketTask) {
        this.setState({ closeResult: str })
        this.state.SocketTask.close()
        this.state.SocketTask = null
      }
    }
    // let height = 64
    // document.body.style.padding = `${height}px 0 0 0`
    // if (Taro.getEnv() == 'SAPP') {

    //  }
  }
  componentWillMount() {
    //   this.getSystemConfig()
    //   // if ( S.getAuthToken() ) {
    //   //   store.dispatch(fetchUserFavs());
    //   // }



  }

  restartOpenWebsoect() {
    let time1 = null;
    let time2 = null;
    console.log('来连接socket了。。。。。')
    time1 = setInterval(() => {
      this.setState({
        meesagestr: ''
      })
      if (this.state.SocketTask) {
        this.state.SocketTask.send({ data: JSON.stringify({ trade_type: 'dsafsdafds' }) })
        console.log('向服务器发送消息========')
        time2 = setTimeout(() => {
          console.log('11232134321111---')
          if (this.state.meesagestr == '') {
            this.setState({
              webSocketIsOpen: false
            })
            if (this.state.SocketTask) {
               this.setState({ closeResult: 'closetoapp' }, ()=>{
                this.state.SocketTask.close()
                this.state.SocketTask = null
              })
           
            }

            console.log('向服务器重新连链接========', this.state.meesagestr)
          }
        }, 30 * 1000);
      } else (
        this.zitiWebsocket()
      )
    }, 3 * 60 * 1000);
    this.zitiWebsocket()
  }

  zitiWebsocket = () => {
    const { webSocketIsOpen, restartOpenWebsoect } = this.state
    let { userInfo } = store.getState().user
    let { distributor_id } = store.getState().planSelection.activeShop
    console.log(store.getState().planSelection.activeShop)
    const token = S.getAuthToken()
    if (!webSocketIsOpen) {
      Taro.connectSocket({
        url: process.env.APP_WEBSOCKET,
        header: {
          'content-type': 'application/json',
        },
        // protocols: [`distributor_id*${distributor_id}&token*${token}&type*distributor`],
        success: function () {
          console.log('連接成功========connect success')
        }
      }).then((task) => {
        this.setState({
          SocketTask: task
        })
        task.onOpen(() => {
          console.log('打开成功========connect success')
          this.setState({
            webSocketIsOpen: true
          })
          task.send({
            data: JSON.stringify({
              'token': `${token}`,
              'type': userInfo.logintype,
              'user_id': userInfo.logintype == 'distributor' ? userInfo.distributor_id : userInfo.merchant_id,
              "event": "save_client",
            })
          })
        })
        task.onError(() => {
          console.log('打开失败========connect error')
          this.setState({
            webSocketIsOpen: false
          })
        })
        task.onMessage((res) => {
          if (res.data === '401001') {
            S.toast('未登录，请登录后再试')
            this.setState(
              {
                webSocketIsOpen: false
              },
              () => {
                setTimeout(() => {
                  S.logout()
                  S.login()
                }, 700)
              }
            )
          } else {
            const message = JSON.parse(res.data)
            this.setState({
              meesagestr: message.trade_type
            })

            console.log('app.js====收到消息', this.state.meesagestr)

            if (this.state.meesagestr == 'dsafsdafds') {
              return
            } else {
              this.setState({
                meesagestr: '服务器心跳'
              })
            }
            if (message.today_data) {
              store.dispatch(updateToday_data(message.today_data))
            }

            // Taro.vibrateLong()

            // let p = plus.audio.createPlayer('https://cdn2.ear0.com:3321/preview?soundid=35835&type=mp3');
            // p.play(function () {
            //   console.log("Audio play success!");
            // }, function (e) {
            //   console.log("Audio play error: " + e.message);
            // });

            switch (message.trade_type) {
              case '0':
                break;
              case '1': {
                if (Taro.getEnv() == 'SAPP') {
                  plus.device.vibrate(500)//手机振动 网页会报错 手机不会
                }
                this.getMessageNum(distributor_id)
                console.log('app.js====收到消息22222', message.trade_type)
                Taro.atMessage({
                  'message': '您收到一条新的订单',
                  'type': 'success',
                })
              }
                break;
              default:
                break;
            }

          }
        })
        task.onClose((e) => {
          this.state.SocketTask = null
          console.log('关闭========connect colse', e)
          this.setState({
            webSocketIsOpen: false
          })
          if (this.state.closeResult == 'closetoapp') {//心跳检测
            console.log('---------closetoapp')
            this.setState({
              closeResult: ''
            })
            console.log('关闭原因', this.state.closeResult)
            this.restartOpenWebsoect()
          }
          // if (restartOpenWebsoect) {
          //记得去重连 这里就算了
          // this.restartOpenWebsocket()
          // // zitiWebsocket()
          // setInterval(() => { 

          // }, 3000);
          // }
        })
      })
    }
  }
  async getMessageNum(distributor_id) {

    const result = await api.message.getMessageList({ distributor_id })
    const { num_type_1, num_type_2, num_type_3 } = result
    let num = Number(num_type_1 ? num_type_1 : 0) + Number(num_type_2 ? num_type_2 : 0) + Number(num_type_3 ? num_type_3 : 0)

    await store.dispatch(updateMessageNum(num.toString()))
    console.log(result)
  }

  onLaunch(options) {
    console.log(`app onLaunch:`, options)
    // setTimeout(() => {
    //   this.zitiWebsocket()
    // }, 2000);
  }

  async componentDidShow(options) {
    if (isWeixin) {
      checkAppVersion()
    }
  }

  componentDidCatchError() { }

  render() {
    return <Provider store={store}>{this.props.children}
      <AtMessage />
    </Provider>
  }
}

export default (App)

